import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LoginView from '../views/LoginView.vue'
import PublicActivitiesView from '../views/PublicActivitiesView.vue'
import ActivityManagementView from '../views/ActivityManagementView.vue'

Vue.use(VueRouter)

// 基础路由
const constantRoutes = [
  {
    path: '/login',
    name: 'login',
    component: LoginView
  },
  {
    path: '/',
    name: 'home',
    component: HomeView,
    meta: { requiresAuth: true }
  },
  {
    path: '/public-activities',
    name: 'public-activities',
    component: PublicActivitiesView,
    meta: { requiresAuth: true }
  },
  {
    path: '/activity-management',
    name: 'activity-management',
    component: ActivityManagementView,
    meta: { requiresAuth: true }
  }
]

// 需要权限的路由
export const asyncRoutes = [
  {
    path: '/public-activities',
    name: 'publicActivities',
    component: () => import('../views/PublicActivitiesView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/public-activities/:id',
    name: 'activityDetail',
    component: () => import('../views/ActivityDetailView.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/activity-management',
    name: 'activityManagement',
    component: () => import('../views/ActivityManagementView.vue'),
    meta: { requiresAuth: true },
    beforeEnter: (to, from, next) => {
      const userRole = localStorage.getItem('userRole')
      if (userRole !== 'admin') {
        alert('对不起，您没有权限访问该页面')
        next('/')
        return
      }
      next()
    }
  }
]

const router = new VueRouter({
  routes: constantRoutes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('isAuthenticated') === 'true'
  
  // 如果要访问登录页且已经登录，重定向到首页
  if (to.path === '/login' && isAuthenticated) {
    next('/')
    return
  }
  
  // 检查是否需要认证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!isAuthenticated) {
      next('/login')
      return
    }
  }
  
  next()
})

export function resetRouter() {
  const newRouter = new VueRouter({
    routes: constantRoutes
  })
  router.matcher = newRouter.matcher
}

export default router